<template>
  <div class="list_dataset">
    <div style="height:100%">
      <div class="dataset_list_content"
           :style="{marginTop:(dataFrom!=='publicApi'&&!isAssetsModel)?'10px':'0'}">
        <!-- content -->
        <div class="list_aside"
             v-show="hideSideBar">
          <div class="sort_checkbox_group">
            <div class="sort_checkbox"
                 @click="selectCondit('sort')">
              <sortConditionComponent :conditionItem="conditionItem"
                                      @sortChange="listColmSort"
                                      @tabTitle="tabSelect"
                                      :options="options"></sortConditionComponent>
            </div>
            <div class="sort_checkbox"
                 @click="selectCondit('filter')">
              <filterConditionComponent :conditionItem="conditionItem"
                                        @tabTitle="tabSelectfilter"
                                        @filterProjectForm="listColmFilter"
                                        :configScript="configScript"></filterConditionComponent>
            </div>
            <div class="sort_checkbox">
              <integrationConditionComponent :integraGpHeihgt="integraGpHeihgt"
                                             @integrationGp="listColmIntegration"
                                             @setShowAllIntegrations="setShowAllIntegrations"></integrationConditionComponent>
            </div>
          </div>
        </div>
        <div class="list_ri_content flex flex-col">
          <div class="flex p-16 items-center">
            <div class="crumbs mr-16"
                 @click="hideSideBar = !hideSideBar"
                 style="width:32px;height:32px;display:flex;align-items: center;justify-content:center;color:#7F7F7FFF;border:1px solid #ccc;border-radius:3px;">
              <div class="cuifont icon_crumbs"
                   :class="hideSideBar?'transform180':'transform0'"></div>
            </div>
            <el-button type="primary"
                       size="small"
                       v-if="$hasPermission('sys:dataset:add')&&dataFrom!=='publicApi'&&!isAssetsModel"
                       @click="addOrUpdateHandle()">{{ $t('custom.widget.new') }}</el-button>
            <el-button type="primary"
                       size="small"
                       v-if="$hasPermission('sys:dataset:sourcetype:sqlagent')&&hasAgent&&dataFrom!=='publicApi'&&!isAssetsModel"
                       @click="addOrUpdateHandle(null,true)">New Agent Dataset</el-button>

            <!-- <NoIntegration type="dataset"
                           ref="no-integration"
                           :params="dataForm"
                           :immediate="false" /> -->

            <el-input placeholder="Search"
                      style="width:280px;margin-left:auto"
                      prefix-icon="el-icon-search"
                      clearable
                      @input="keyWordsChange"
                      v-model="keyWords">
            </el-input>

          </div>

          <div class="flex-1  h-0 py-16 pl-16"
               v-loading="dataListLoading">
            <cardList ref="cardList"
                      v-if="!!comDataList.length"
                      :comDataList="comDataList"
                      :configScript="configScript"
                      :pageTotal="pageTotal"
                      :size="size"
                      :current="current"
                      :isReportAdd="dataFrom==='publicApi'"
                      :currListPage="dataForm.current"
                      :currListSize="dataForm.size"
                      @emitCurrPage="emitCurrPageChange"
                      @emitCurrSize="emitCurrSizeChange"
                      @deleteHandleItem="deleteHandleItem"
                      @showLinkedBotDialog="showLinkedBotDialog"
                      @showLinkedDialog="showLinkedDialog"
                      @cardQuery="cardQuery"
                      :selectionRows="selectionRows"
                      @event:addSelected="addSelected"
                      @editHandle="editHandle"></cardList>
            <div v-else
                 class="flex flex-col items-center justify-center h-full">

              <div class="no_data_img"></div>
              <div>No dataset found</div>
            </div>

          </div>
        </div>
        <add-or-update v-if="addOrUpdateVisible"
                       ref="addOrUpdate"
                       @newDatasetRouter="jumpNewDatasetPage"
                       @refreshDataList="getDataList"></add-or-update>
        <data-set-management v-if="Datasetshow"
                             ref="Datasetshow"></data-set-management>
        <linked-widget v-if="linkWidgetVisible"
                       ref="linkWidget"
                       @refreshDataList="getDataList"></linked-widget>
        <linked-bot v-if="linkBotVisible"
                    ref="linkBot"
                    @refreshDataList="getDataList"></linked-bot>
      </div>
    </div>
  </div>
</template>
<script>
import AddOrUpdate from './add-or-update'
import mixinViewModule from '@/mixins/crud-view-module'
import LinkedWidget from './components/linked-widget'
import sortConditionComponent from '@/components/viewComponents/sort-condition.vue'
import filterConditionComponent from '@/components/viewComponents/filter-condition.vue'
import cardList from '@/components/viewComponents/card-list.vue'
import integrationConditionComponent from '@/components/viewComponents/intergration-condition.vue'


export default {
  props: {
    selectionRows: {
      type: Array,
      default: () => ([])
    },
    showDashboardType: {
      type: String
    },
    datasetResourceType: {
      type: Number,
      default: 5
    }

  },
  components: {
    sortConditionComponent,
    filterConditionComponent,
    integrationConditionComponent,
    cardList,
    AddOrUpdate,
    LinkedWidget,


  },
  mixins: [mixinViewModule],
  inject: {dataFrom:{default:''},isAssetsModel: {default: false},isDefaultRole: {default:false}},
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/web/reports/sys/dataset/list',
        getDataListURLCard: '/web/reports/sys/dataset/card-list',

        getDataListIsPage: false,
        deleteURL_other: '/web/reports/sys/dataset/',
        deleteIsBatch: false,
        exportURL: ''
      },
      dataForm: {
        showAllIntegration: false,
        internal: this.IsInternal()
        // current: 1,
        // size: 10
      },
      groupOptions: { columns: ['integration'] },
      pageSettings: { pageSize: 100, pageSizes: [50, 100, 200, 1000], pageCount: 4 },
      loading: false,
      sortSettings: {
        columns: [
          { field: 'name', direction: 'Ascending' }
        ]
      },
      linkBotVisible: false,
      Datasetshow: false,
      viewValue: 'List',
      viewValueList: [{ label: 'Grid', value: 'Grid', icon: 'cuifont icon_table' }, { label: 'List', value: 'List', icon: 'cuifont icon_list' }],
      options: [
        {
          value: 'name',
          label: 'Name'
        },
        {
          value: 'status',
          label: 'Status'
        },
        {
          value: 'business_type',
          label: 'Type'
        },
        {
          value: 'lastSyncDate',
          label: 'Last Synced'
        },
        {
          value: 'modelNum',
          label: 'Linked Widgets'
        },
        {
          value: 'create_date',
          label: 'Created Date'
        },
        {
          value: 'creatorName',
          label: 'Creator'
        },
        {
          value: 'update_date',
          label: 'Last Modified'
        },
        {
          value: 'updateByName',
          label: 'Last Modified By'
        }
      ],
      keyWords: '',
      // keyWordsValue: '',

      conditionItem: '',
      hideSideBar: true,
      configScript: {
        id: 'id',
        name: 'name',
        status: 'status',
        description: 'description',
        businessType: 'businessType',
        icon: 'icon',
        botNum: 'botNum',
        modelNum: 'modelNum',
        integration: 'integration',
        createDate: 'createDate',
        creatorName: 'creatorName',
        updateDate: 'updateDate',
        updateByName: 'updateByName',
        lastSyncDate: 'lastSyncDate',
        ownerName: 'ownerName',
        Permission: 'dataset'
      },
      filterProject: {
        'order': [
          { 'field': 'update_date', 'sort': 'DESC' }
        ],
        'filter': {
          'type': [],
          'status': [],
          'modelNum': { 'min': '', 'max': null },
          'lastSyncDate': {
            'from': '',
            'to': ''
          },
          'createDate': {
            'from': '',
            'to': ''
          },
          'updateDate': {
            'from': '',
            'to': ''
          },
          'creator': [],
          'updateBy': []
        },
        'integrationGroup': []
      },
      source: null,
      integraGpHeihgt: null
    }
  },
  computed: {
    comDataList () {
      let path = window.location.pathname
      var retdata = []
      if (path === '/SystemDataset' && this.IsInternal()) {
        retdata = this._.filter(this.dataList, { businessType: 'System' })
      } else if(this.isDefaultRole&&this.isDefaultRole()){
        retdata = this.dataList.filter(i=>i.businessType === 'Template')
      }else {
        retdata = this.dataList
      }
      // retdata = retdata.filter(item => {
      //   if (this.keyWordsValue) {
      //     if (item.description) {
      //       return item.name.toLowerCase().includes(this.keyWordsValue.toLowerCase()) || item.description.toLowerCase().includes(this.keyWordsValue.toLowerCase())
      //     } else {
      //       return item.name.toLowerCase().includes(this.keyWordsValue.toLowerCase())
      //     }
      //   } else {
      //     return item
      //   }
      // })
      return retdata.map(v => {
        return {
          ...v,
          checked: this.selectionRows.find(i => i.resourceId === v.id) && true
        }
      })
    },
    hasAgent () {

      let integrationList = this.$store.state.user.integrationList.filter(item=>item.group < 3) || []

      return !!integrationList.filter(i => i.subjectCode === 'SQLAGENT' || i.subjectCode === 'AUTOMATEAGENT'|| i.subjectCode === 'KVSAONPREMISE'|| i.subjectCode === 'CWMONPREMISE'|| i.subjectCode === 'CWAUTOONPREMISE').length
    }
  },
  created () {
    try {
      if(this.isDefaultRole&&this.isDefaultRole()) {
        this.filterProject.filter.type = ['Template']
      }
      if (this.$route.path === '/Datasets') {
        this.filterProject.filter.type = ['Custom', 'Template']
      } else if (this.$route.path === '/SystemDataset') {
        this.filterProject.filter.type = []
        this.filterProject.filter.type.push('System')
      } else if (this.$route.path === '/CrossTenantDataset') {
        this.filterProject.filter.type = []
        this.filterProject.filter.type.push('MSPbots Internal')
      }
    } catch (error) {
      //  console.log(error);
    }

    this.cardQuery()
  },
  mounted () {
    this.tabSelect({ tab: false, text: 'sort' })

  },
  methods: {
    addSelected (rows) {
      this.$emit('event:addSelected', rows)
    },
    tabSelect (val) {
      let height = document.querySelector('.list_aside').offsetHeight
      if (val.text === 'sort' && val.tab) {
        this.integraGpHeihgt = height - 10 - 121 - 60 - 80
      }
      if (val.text === 'sort' && !val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 60 - 80
      }
      this.$forceUpdate()
    },
    tabSelectfilter (val) {
      let height = document.querySelector('.dataset_list_content').offsetHeight
      if (val.text === 'filter' && val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 80 - 554
      }
      if (val.text === 'filter' && !val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 60 - 80
      }
      this.$forceUpdate()
    },
    // keyWordsChange: debounce(function (val) {
    //   this.keyWordsValue = val
    //   if (this.$refs.cardList) this.$refs.cardList.scrollTop()
    // }, 1000),
    listColmSort (val) {
      this.filterProject.order = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery()
    },
    listColmFilter (val) {
      this.filterProject.filter = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    listColmIntegration (val) {
      this.filterProject.integrationGroup = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    setShowAllIntegrations (val) {
      this.dataForm.showAllIntegration = val

      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    loadComDataList () {
      this.pageSize += 10
    },
    selectCondit (val) {
      this.conditionItem = val
    },
    jumpNewDatasetPage (row) {
      this.showDataset(row)
    },
    emitCurrPageChange (page) {
      this.dataForm.current = page
      this.cardQuery()
    },
    emitCurrSizeChange (size) {
      this.dataForm.size = size
      this.cardQuery()
    },
    editHandle (row, activeTab) {
      if (!this.$hasPermission('sys:dataset:edit') || !this.$hasPermissionRouterName(('dataset-' + row.name).replace(/ /g, ''))) {
        return this.$message.error(this.$t('prompt.nopermission'))
      }
      this.addOrUpdateHandle(row.id, row.language === 'sqlagent', activeTab)
    },
    deleteHandleItem (row) {
      if (!this.$hasPermission('sys:dataset:delete') || !this.$hasPermissionRouterName(('dataset-' + row.name).replace(/ /g, ''))) {
        return this.$message.error(this.$t('prompt.nopermission'))
      }
      if (row.modelNum !== 0) {
        this.showLinkedDialog(row)
      } else {
        this.deleteHandle(row.id)
      }
    },
    showLinkedDialog (row) {
      this.linkWidgetVisible = true
      this.$nextTick(() => {
        this.$refs['linkWidget'].dataForm.id = row.id
        this.$refs['linkWidget'].init()
      })
    },
    showLinkedBotDialog (row) {
      this.linkBotVisible = true
      this.$nextTick(() => {
        this.$refs['linkBot'].dataForm.dataSourceId = row.id
        this.$refs['linkBot'].init()
      })
    },
    showDataset (data) {
      this.$router.push({ path: `dataset-${data.id}`, query: { pageid: `${data.id}`, name: data.name } })
    },
    formatDataList () {
      // this.dataList
      let tempList = []
      this.dataList.map(e => {
        if (e.configStatus && e.configStatus.status === 1) {
          tempList.push(e)
        }
      })
      return tempList
    },
    changeShowAllIntegration () {
      if (this.$refs.cardList) this.$refs.cardList.scrollTop()
      this.cardQuery()
    },
    IsInternal () {
      // let path = window.location.pathname
      if (this.showDashboardType === 'InternalDataset' || this.showDashboardType === 'SystemDataset') {
        return true
      } else {
        return false
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.meta.name === from.meta.name) {
      if (this.$store.state.contentTabs.findIndex(item => item.name === to.name) > -1) {
        this.$set(
          this.$store.state.contentTabs,
          this.$store.state.contentTabs.findIndex(item => item.name === to.name),
          { ...this.$store.state.contentTabs[this.$store.state.contentTabs.findIndex(item => item.name === to.name)], title: to.meta.title }
        )
      }
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.crumbs {
  cursor: pointer;
  background-image: url("#{$--ossLink}/app/view_pageheader/crumbs.png");
  background-size: 14px;
  background-position: center;
  background-repeat: no-repeat;
}
.crumbs:hover {
  border-radius: 4px;
  border: 1px solid #138dc7 !important;
  background: #e6f7ff;
}
.icon_crumbs {
  width: 14px;
  height: 14px;
}
.crumbs:hover .icon_crumbs {
  background-image: url("#{$--ossLink}/app/view_pageheader/show_aside.png");
  background-size: 14px;
  background-position: center;
  background-repeat: no-repeat;
}
.transform0 {
  transform: rotate(0deg);
}
.transform180 {
  transform: rotate(180deg);
}
.list_dataset {
  height: 100%;
  .dataset_list_content {
    height: 100%;
    background-color: #fff;
    // margin-top: 10px;
    border-radius: 4px;
    // height: calc(100% - 60px);

    .list_aside {
      display: flex;
      flex-direction: column;
      height: 100%;
      width: 283px;
      float: left;
      padding: 16px 0px;
      box-shadow: 1px 0px 0px 0px #f0f0f0;
      overflow: hidden;

      transition: 1s width;
      .sort_checkbox_group {
        overflow-y: auto;
        flex: 1;
      }
    }
    .list_ri_content {
      transition: 1s width;
      height: 100%;

      .no_data_img {
        width: 164px;
        height: 99px;
        margin-bottom: 5px;
        background-image: url("#{$--ossLink}/app/view_pageheader/dataset_nodate.png");
        background-repeat: no-repeat;
        background-size: 164px 99px;
        background-position: center;
      }
      .no_data_text {
        margin-bottom: 10px;
        height: 20px;
        font-size: 14px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.5);
        line-height: 20px;
      }
      .no_data_intro {
        width: 200px;
        height: 34px;
        font-size: 12px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.25);
        line-height: 17px;
        text-align: center;
        margin-bottom: 10px;
      }
      .widget-library--text {
        color: #17b3a3;
        text-decoration: underline;
      }
    }
  }
}
</style>
